#############################################
#This file creates Figure 2
#############################################

###Log
my_log <- file("figure2_log.txt")

sink(my_log, append=T, type="output")
sink(my_log, append=T, type="message")

cat(readChar(rstudioapi::getSourceEditorContext()$path, # Writing currently opened R script to file
             file.info(rstudioapi::getSourceEditorContext()$path)$size))

start_time <- Sys.time()
start_time

############################
#Packages
############################
library(rio)
library(scales)
library(psych)
library(tidyverse)
library(broom)
library(ggstance)
library(socviz)
library(car)
library(magrittr)
library(multcomp)
library(margins)

############################
#Experiment 2
############################

####Load the data
exp2 <- import("./Data/exp2_cleaned.csv")

####Clean the data as needed
#DV
exp2$support01 <- scales::rescale(exp2$policy_support)

#Treatment Condition(s)
exp2 <- exp2 %>%
  mutate(treat = case_when(
    treat_info == 1 ~ 1, 
    treat_info == 2 ~ 2, 
    treat_info == 4 ~ 3)) %>%
  mutate(treat = factor(treat, 
                        labels=c("No Party Cue", "Party Cue", 
                                 "Cue w/Insinuation")))


exp2$stereo <- factor(exp2$treat_policy_congruence, 
                      levels=c(0,1),
                      labels=c("Counter-Stereotypical", "Stereotypical"))

#Experiment
exp2$experiment <- "Experiment 2"
exp2$pol_exp <- NA
exp2$pol_exp[exp2$treat_policy==0] <- "Tax:Conservative"
exp2$pol_exp[exp2$treat_policy==1] <- "Tax:Liberal"

############################
#Experiment 3
############################

####Load the data
exp3 <- import("./Data/exp3_cleaned.csv")

####Clean the data as needed
#restrict to partisans
exp3 <- exp3 %>%
  filter(pid_3 == "Democrat" | pid_3 == "Republican")

#DV
exp3$support01 <- scales::rescale(exp3$tax_support)

#Treatment Condition(s)
exp3$treat <- factor(exp3$treat_3, 
                     levels=c("No Party Cue", "Party Cue", "Party Cue w/ Group Pressure"), 
                     labels=c("No Party Cue", "Party Cue", "Cue w/Insinuation"))

exp3$stereo <- factor(exp3$change_stereotype, 
                      levels=c("Non-Stereotypical Change", "Stereotypical Change"), 
                      labels=c("Counter-Stereotypical", "Stereotypical"))

#Experiment
exp3$experiment <- "Experiment 3"

############################
#Binding
############################

########Binding
exp2a <- exp2 %>%
  dplyr::select(support01, treat, experiment, stereo) 
exp3a <- exp3 %>%
  dplyr::select(support01, treat, experiment, stereo) 

pooled <- rbind(exp2a, exp3a)

pooled$experiment <- factor(pooled$experiment, 
                            levels=c("Experiment 2", "Experiment 3"))

#Export to Stata, for table creation and for difference in marginal 
#effects lincom estimates. Need to run the Stata file before 
#the below.
export(pooled, "./Figure2/figure2_pooled.dta")

############################
#Models
############################
m1 <- lm(support01 ~ treat*stereo + experiment , data = pooled)
m2 <- lm(support01 ~ treat*stereo, data = pooled, subset=(experiment == "Experiment 2"))
m3 <- lm(support01 ~ treat*stereo, data = pooled, subset=(experiment == "Experiment 3"))


###Marginal effect
#Function
margs <- function(x) {
  summary(margins(x, 
                  at=list(stereo=c("Counter-Stereotypical", "Stereotypical")), 
                  variables="treat"))
}

#extract
m1m <- margs(m1)
m2m <- margs(m2)
m3m <- margs(m3)

m1m <- as.data.frame(m1m)
m2m <- as.data.frame(m2m)
m3m <- as.data.frame(m3m)

m1m$model <- "Pooled"
m2m$model <- "Experiment 2"
m3m$model <- "Experiment 3"

m_margins <- rbind(m1m, m2m, m3m) %>%
  dplyr::select(-z) 

m_margins$factor <- prefix_strip(m_margins$factor, "treat")

####Difference in Coefficients
#' Unfortunately, not sure how this can be done in R. So, we turn to STATA to 
#' calculate the differences! See figure2_table.do for the creation of the
#' subsequently used datafiles.

#Cleaning function 
diff_func <- function(x) {
  x %>%
    dplyr::mutate(factor = "Difference") %>%
    dplyr::rename(AME = estimate, 
                  SE = stderr, 
                  lower = min95, 
                  upper = max95) %>%
    dplyr::select(-c(parm, label, dof, t))
}


####Model 1 Data
#stereotypical
m1_stereo <- import("./Figure2/pooled_stereotypical.dta") %>%
  mutate(stereo = "Stereotypical", 
         model = "Pooled") 

m1_stereo <-  diff_func(m1_stereo)

#counter-stereotypical
m1_counter <- import("./Figure2/pooled_counterstereotypical.dta") %>%
  mutate(stereo = "Counter-Stereotypical", 
         model = "Pooled")

m1_counter <- diff_func(m1_counter)

##Model 2
m2_stereo <- import("./Figure2/exp2_stereotypical.dta") %>%
  mutate(stereo = "Stereotypical", 
         model = "Experiment 2") 

m2_stereo <-  diff_func(m2_stereo)

#counter-stereotypical
m2_counter <- import("./Figure2/exp2_counterstereotypical.dta") %>%
  mutate(stereo = "Counter-Stereotypical", 
         model = "Experiment 2")

m2_counter <- diff_func(m2_counter)

##Model 3 Data
#stereotypical
m3_stereo <- import("./Figure2/exp3_stereotypical.dta") %>%
  mutate(stereo = "Stereotypical", 
         model = "Experiment 3") 

m3_stereo <-  diff_func(m3_stereo)

#counter-stereotypical
m3_counter <- import("./Figure2/exp3_counterstereotypical.dta") %>%
  mutate(stereo = "Counter-Stereotypical", 
         model = "Experiment 3")

m3_counter <- diff_func(m3_counter)

######Binding
margins_comb <- rbind(m_margins, 
                      m1_stereo, m1_counter, 
                      m2_stereo, m2_counter, 
                      m3_stereo, m3_counter)

margins_comb <- margins_comb %>%
  mutate(sig = if_else(lower > 0, "Significant p < 0.05", "Insignificant p >= 0.05"))

margins_comb <- margins_comb %>%
  mutate(factor = factor(factor, 
                         levels=c("Party Cue", "Cue w/Insinuation" , "Difference")))

margins_comb <- margins_comb %>%
  mutate(model = factor(model, 
                        levels=c("Pooled", "Experiment 2", "Experiment 3")))

#########Figure
margins_comb <- margins_comb %>%
  mutate(factor1 = factor(factor, 
                          levels=c("Difference", "Cue w/Insinuation", "Party Cue"), 
                          labels=c("Diff. in Coefs", "Cue w/Insinuation", "Party Cue")), 
         stereo1 = factor(stereo, 
                          levels=c("Stereotypical", "Counter-Stereotypical"),
                          labels=c("Stereotypical Policy Change", "Counter-Stereotypical Policy Change")))

margins_comb %>%
  ggplot(aes(x=AME, y=factor1, shape = sig)) + 
  geom_pointrangeh(aes(xmin=lower, xmax=upper)) + 
  theme_bw(18) + 
  facet_grid(stereo1 ~ model, 
             labeller = label_wrap_gen(width = 15)) + 
  geom_text(data=margins_comb, aes(label=round(AME,2)), 
            nudge_y=0.15)  + 
  theme(strip.text.y = element_text(angle=0), 
        legend.position="bottom") + 
  scale_shape_manual(values=c(1,16)) + 
  labs(x = NULL,
       y = NULL, 
       shape = "Statistically Significant?") + 
  geom_vline(xintercept=0, 
             linetype="dashed", 
             color="red") + 
  scale_x_continuous(breaks=c(0, 0.1))

ggsave("./Figure2/figure2.png", height=7, width=14)


end_time <- Sys.time()
end_time

closeAllConnections()
